package com.thinkwide.data.ormapping.datatable;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

public class MFDTConvert {
    public static String toString(Object o) {
        return toString(o, "");
    }

    public static String toString(Object o, String defValue) {
        if (o == null)
            return defValue;
        return o.toString();
    }

    public static int toInt(Object o) {
        return toInt(o, 0);
    }

    public static int toInt(Object o, int defValue) {
        if (o == null)
            return defValue;
        if (o instanceof Integer)
            return ((Integer) o).intValue();

        try {
            return (int) Float.parseFloat(o.toString());
        } catch (Exception e) {
            return defValue;
        }
    }

    public static long toLong(Object o) {
        if (o == null)
            return 0L;
        if (o instanceof Long)
            return ((Long) o).longValue();

        try {
            return Long.parseLong(o.toString());
        } catch (Exception e) {
            return 0L;
        }
    }

    public static BigDecimal toBigDecimal(Object o) {
        if (o == null)
            return BigDecimal.ZERO;
        if (o instanceof BigDecimal)
            return ((BigDecimal) o);

        try {
            return new BigDecimal(o.toString());
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }


    public static double toDouble(Object o) {
        if (o == null)
            return 0F;
        if (o instanceof Double)
            return ((Double) o).doubleValue();

        try {
            return Double.parseDouble(o.toString());
        } catch (Exception e) {
            return 0F;
        }
    }

    public static float toFloat(Object o) {
        if (o == null)
            return 0F;
        if (o instanceof Float)
            return ((Float) o).floatValue();

        try {
            return Float.parseFloat(o.toString());
        } catch (Exception e) {
            return 0F;
        }
    }

    public static boolean toBool(Object o) {
        if (o == null)
            return false;
        if (o instanceof Boolean)
            return ((Boolean) o).booleanValue();

        try {
            return Boolean.parseBoolean(o.toString());
        } catch (Exception e) {
            return false;
        }
    }

    public static Date toDate(Object o) {
        return toDate(o, new Date(System.currentTimeMillis()));
    }

    public static Date toDate(Object o, Date defValue) {
        if (o == null)
            return defValue;

        if (o instanceof Date)
            return (Date) o;

        try {
            return Timestamp.valueOf(o.toString());
        } catch (Exception e) {
            return defValue;
        }
    }
}